package com.inno.lock.processor.single;

import com.inno.lock.processor.annotiation.SingleLock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 分布式锁切面
 *
 * @author shenzeyang
 */
@Aspect
@Component
public class SingleLockAspect {

    private static  ReentrantLock LOCK = new ReentrantLock();
    @Pointcut("@annotation(com.inno.lock.processor.annotiation.SingleLock)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        SingleLock lockEnum = method.getAnnotation(SingleLock.class);
        if (lockEnum.fair()){
            LOCK = new ReentrantLock(true);
        }
        if (LOCK.tryLock(lockEnum.timeout(), lockEnum.timeUnit())){
            try {
                return point.proceed();
            }finally {
                LOCK.unlock();
            }
        }
        throw new IllegalArgumentException("请稍后重试");

    }
}
